<template>
  <div class="w-100vw h-100vh overflow-hidden realative">
    <div v-show="booleanStore.headerTopShow">
      <div class="header-container"></div>
      <div class="absolute top-20px right-40px z-1000 flex items-center justify-between">
        <div class="flex items-center text-16px text-#fff">
          <div :class="[
            'w-47px h-36px flex items-center justify-center',
            dimensions === '2d' ? 'dimensions-a' : 'dimensions',
          ]" @click="changeDimensions('2d')">
            2D
          </div>
          <div :class="[
            'w-47px h-36px flex items-center justify-center ml-[-15px]',
            dimensions === '3d'
              ? 'dimensions-a rotate-180'
              : 'dimensions rotate-180',
          ]" @click="changeDimensions('3d')">
            <span class="inline-block -rotate-180">3D</span>
          </div>
        </div>
        <div class="login-out w-110px h-32px px-8px box-border text-#fff flex items-center justify-center mx-20px"
          v-hover-show="'#tooltipBox'">
          <img class="mr-5px" src="@/assets/img/home/icon-2.png" />个人中心
        </div>
        <div @click="handleLogout"
          class="login-out w-110px h-32px px-8px box-border text-#fff flex items-center justify-center">
          <img class="mr-5px" src="@/assets/img/home/icon-1.png" />退出登录
        </div>
      </div>
    </div>
    <LeftSideCharts />
    <RightSideCharts :hotByAddress="hotByAddress" />
    <!-- <Searchmonitoring /> -->

    <!-- cesium画布元素 -->
    <div id="cesiumContainer"></div>

    <div class="absolute top-10% left-50% translate-x-[-50%] flex z-1" v-show="booleanStore.headerTopShow">
      <!-- <div v-if="a"> -->
      <el-date-picker popper-class="popperClass" v-model="date" type="daterange" start-placeholder="开始日期"
        end-placeholder="结束日期" unlink-panels :shortcuts="shortcuts" @change="loadData(clickToolType)"/>
    </div>
    <div v-show="booleanStore.footerBottomShow">
      <!-- 底部按钮组：使用grid布局 -->
      <div class="footer absolute bottom-0 left-0 w-full h-162px z-2">
        <div class="relative w-full h-full">
          <div class="arc-btn w-99px h-80px flex flex-col items-center justify-center" @click="btnClick(i.type)" :style="{
            position: 'absolute',
            left: `${i.left}px`,
            bottom: `${i.bottom}px`,
          }" v-for="i in BTN_LIST" :key="i.type">
            <img :src="getAssets(i.type + '.png')" class="w-32px h-32px mb-7px" />
            <span class="text-16px text-#fff">{{ i.label }}</span>
            <!-- tool -->
            <div v-show="showTool(i.type)"
              class="tool-btn w-210px h-90px flex justify-center items-center absolute bottom-100% left-50% translate-x-[-50%]">
              <div v-for="item in TOOL_LIST[i.type]" :key="item.type">
                <div v-show="showToolList(item.type)" class="flex flex-col items-center mb-25px mt-5px mr-10px ml-10px"
                  @click.stop="loadData(item.type)">
                  <img :src="getAssets(item.type + '.png')" class="w-32px h-32px" />
                  <span class="text-12px text-#fff">{{ item.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <MonitorTableList />
    <!-- 热力图绘制面点击弹窗 -->
    <RectangleDialog :time-data="date" />
    <img src="@/assets/img/log.png" alt="icon" class="absolute bottom-0 left-10px w-1.5 h-0.5 z-10" />
    <VideoPlayer v-if="showVideo" @closeVideo="showVideo = false" :source="video.source" :info="video.info" />
  </div>
  <PersonalCenter id="tooltipBox" v-show="false" />
</template>

<script setup lang="ts">
import { modelList } from "@/const/mapConfig";
import { BTN_LIST, TOOL_LIST } from "@/const/home";
import { getAssets, jianKongUrl, toPage } from "@/utils";
import CesiumInit from "@/utils/cesium/CesiumInit";
import { eventTarget } from "@/utils/cesium/PrimitiveLoader";
import * as MapApi from "@/service/api/map";
import { AccidentDimension } from "@/service/api/SamplInterface";
import { useMonitorTableList, useLogin, jurisdiction, useBoolean } from "@/store";
import dayjs from "dayjs";
import LeftSideCharts from "./leftSideCharts/index.vue";
import RightSideCharts from "./rightSideCharts/index.vue";
import RectangleDialog from "./rectangleDialog/index.vue";

const worker = new Worker(
  new URL("../../workers/mapDataWorker.ts", import.meta.url),
  { type: "module" }
);

interface WorkerResponse {
  type: "batch" | "complete";
  data: Array<{ position: string; image: string }> | number;
}

let primitiveLoader, draw;
const shortcuts = [
  {
    text: '半年',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 6);
      return [start, end];
    },
  },
  {
    text: '一年',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 12);
      return [start, end];
    },
  },
  {
    text: '三年',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 36);
      return [start, end];
    },
  },
];

const login = useLogin();
const jur = jurisdiction();
const monitorTable = useMonitorTableList();
const booleanStore = useBoolean();
const date = ref<[Date, Date]>([
  dayjs('2024-11-01').toDate(),
  dayjs('2025-01-31').toDate(),
]); // 日期范围
const clickBtnType = ref<(typeof BTN_LIST)[number]["type"] | any>(null); // 点击的按钮类型
const clickToolType = ref<
  (typeof TOOL_LIST)[keyof typeof TOOL_LIST][number]["type"] | any
>(null); // 点击的工具类型
const dimensions = ref<"2d" | "3d">("2d");
const showVideo = ref(false);
const video = reactive<any>({
  source: "",
  info: null,
});
const hotByAddress = ref<any>();

// 监控点位点击事件
eventTarget.on("monitorClick", function (event: any) {
  handleSelect(event);
});

// 监听 Worker 消息
worker.addEventListener("message", (e: MessageEvent<WorkerResponse>) => {
  const { type, data } = e.data;
  const { primitiveLoader, map3d } = window.cesiumInit;
  if (type === "batch") {
    const image = getAssets(data[0].image + "Marker.png");
    // 处理每一批数据
    (data as Array<{ position: string; image: string }>).forEach((item) => {
      if (item.image === "construction") {
        primitiveLoader.addPrimitiveLayer(item.position);
      }
      primitiveLoader.addPointPrimitive(item.position, image, {
        ...item,
        type,
      });
    });
    map3d.camera.zoomOut(1);
  } else if (type === "complete") {
    console.log(`处理完成，共处理 ${data} 条数据`);
  }
});

// 对应得tool弹窗显示   ai只能跟多项分析不显示tool弹窗
const showTool = computed(() => (type) => {
  return (
    type === clickBtnType.value &&
    type !== "multipleAnalysis" &&
    type !== "intelligence" &&
    booleanStore.footerToolShow
  );
});

// 是否显示绘制与删除绘制按钮
const showToolList = computed(() => (type: string) => {
  if (
    clickBtnType.value !== "statisticHeatMap" &&
    (type === "draw" || type === "deleteDraw")
  ) {
    return clickToolType.value && clickToolType.value !== clickBtnType.value;
  }
  return true;
});

// 按钮点击事件
const btnClick = (type: (typeof BTN_LIST)[number]["type"]) => {
  primitiveLoader.clearAllMapLayers(); // 清除所有图层
  draw.removeAll(); // 清除所有绘制

  clickBtnType.value = type === clickBtnType.value ? null : type;
  booleanStore.setFooterToolShow(clickBtnType.value ? true : false); // 设置底部工具栏是否显示
  clickToolType.value = null; //清空数据避免绘制与清除绘制一直显示

  switch (type) {
    case "multipleAnalysis":
      toPage("/multiple-analysis-reports", {
        startTime: dayjs(date.value[0]).format("YYYY-MM-DD"),
        endTime: dayjs(date.value[1]).format("YYYY-MM-DD"),
      });
      break;
    case "intelligence":
      toPage("/aiModel");
      break;
    case "monitor": // 监控点击清空数据
      !clickBtnType.value && monitorTable.setState(false, "", []);
      break;
    default:
      if (clickBtnType.value === "statisticHeatMap") {
        // 直接加载热力图数据
        loadData(clickBtnType.value);
      }
      break;
  }
  // typeProps.value = type;
};

const loadData = async (
  type:
    | (typeof TOOL_LIST)[keyof typeof TOOL_LIST][number]["type"]
    | "statisticHeatMap" // 接收工具类型参数
) => {
  if (clickBtnType.value === "monitor") {
    primitiveLoader.clearAllMapLayers(); // 清除所有图层
    monitorTable.setState(false, "", []);
    monitorTable.setShowArrow(false);
  }
  draw.removeAll(); // 清除所有已绘制的图形

  clickToolType.value = type; // 更新当前点击的工具类型

  // 如果工具类型是 "draw"，绘制矩形并返回
  if (type === "draw") {
    draw.drawRectangle(clickBtnType.value); // 根据当前按钮类型绘制矩形
    if (clickBtnType.value === "monitor") {
      monitorTable.setState(false, "", []);
    }
    return;
  } else if (type === "deleteDraw") {
    // 如果工具类型是 "deleteDraw"，直接返回
    if (clickBtnType.value === "monitor") {
      primitiveLoader.clearAllMapLayers();
      monitorTable.setState(false, "", []);
      monitorTable.setShowArrow(false);
    }
    return;
  }
  primitiveLoader.clearAllMapLayers(); // 清除相关图层和图形
  const dateRange = getDateRange(); // 获取日期范围

  hotByAddress.value = type === 'statisticHeatMap' ? await fetchMapData('analysisByAddress', { ...dateRange, minPoints: '6' }) : [];// 获取事故热点位置

  const data =
    type !== "statisticHeatMap"
      ? type === "monitor"
        ? await MapApi.GetSearchMonitoring()
        : await fetchMapData(type, dateRange)
      : await AccidentDimension(dateRange);

  if (type === 'monitor') {
    monitorTable.setState(true, type, data);
  }

  // 存储开始时间和结束时间
  localStorage.setItem("dateRange", JSON.stringify(dateRange));
  // 如果工具类型包含 "HeatMap"，处理热力图数据
  if (type.includes("HeatMap")) {
    // if (type === "accidentHeatMap") {
    //   // 如果是事故热力图，遍历数据并处理每一组数据
    //   console.log(data, 'data');
    //   data.forEach((item) => {
    //     handleHeatMapData(item.data, draw, primitiveLoader);
    //   });
    // } else {
      // 其他类型的热力图，直接处理数据
      handleHeatMapData(data, draw, primitiveLoader);
    // }
  } else {
    // 如果不是热力图，将数据发送到 Worker 进行处理
    worker.postMessage({ data, type });
  }
};

const fetchMapData = async (
  type: string,
  params: { startTime: string; endTime: string; minPoints?: string }
) => {
  const apiMap = {
    accident: MapApi.GetAccident,
    construction: MapApi.GetConstruction,
    alarm: MapApi.GetAlarm,
    vioSurveil: MapApi.GetVioSurveil,
    deathAccident: MapApi.GetDeathAccident,
    // accidentHeatMap: MapApi.GetAccidentHeatMapByReason,
    accidentHeatMap: MapApi.GetAccidentHeatMap,
    constructionHeatMap: MapApi.GetConstructionHeatMap,
    alarmHeatMap: MapApi.GetAlarmHeatMap,
    vioSurveilHeatMap: MapApi.GetVioSurveilHeatMap,
    statisticHeatMap: MapApi.GetstatisticHeatMap,
    monitorHeatMap: MapApi.GetSearchMonitoring,
    analysisByAddress:MapApi.GetAnalysisByAddress,
    deathAccidentHeatMap: MapApi.GetDeathAccidentHeatMap,
  };

  return await apiMap[type](params);
};

const handleHeatMapData = (data: any[], draw: any, primitiveLoader: any) => {
  const arrPoints = data.map((item) => ({
    lng: item.longitude,
    lat: item.latitude,
    value: item.count,
  }));

  data.forEach((item) => {
    draw.addData(`${item.longitude},${item.latitude}`, { ids: item.ids });
  });

  primitiveLoader.loadHeatmap(arrPoints);
};

const getDateRange = () => {
  if (date.value && date.value[0] && date.value[1]) {
    return {
      startTime: dayjs(date.value[0]).format("YYYY-MM-DD") + " 00:00:00",
      endTime: dayjs(date.value[1]).format("YYYY-MM-DD") + " 23:59:59",
    };
  }
  return {
    startTime: dayjs().subtract(30, "day").format("YYYY-MM-DD") + " 00:00:00",
    endTime: dayjs().format("YYYY-MM-DD") + " 23:59:59",
  };
};

const changeDimensions = (value: "2d" | "3d", form = "") => {
  dimensions.value = value;
  if (value === "3d") {
    modelList.forEach((item) => {
      window.cesiumInit.modelAndImage.addCesium3DTileSet(item);
    });
  } else {
    window.cesiumInit.modelAndImage.delete3DTile();
  }
  if (form === "rectangle-dialog") {
  } else {
    // 清空热力图
    window.cesiumInit.primitiveLoader.removeHeatLayer();
    // 重新加载热力图
    clickBtnType.value && loadData(clickBtnType.value);
  }
};
// 退出登录处理函数
const handleLogout = () => {
  // 清除本地存储
  localStorage.removeItem("userInfo");
  // 重置登录状态
  login.resetState();
  // 重置权限状态（若jurisdiction有resetState方法）
  if (jur.resetState) jur.resetState();
  // 跳转登录页
  toPage("/login");
};

// 选项选择处理函数
const handleSelect = async (item: Record<string, any>) => {
  const res = await jianKongUrl(item.deviceId);
  if (res) {
    showVideo.value = true;
    video.source = res;
    video.info = item;
  }
};

onMounted(() => {
  window.cesiumInit = new CesiumInit();
  window.cesiumInit.loadData();
  ({ primitiveLoader, draw } = window.cesiumInit);
});

onUnmounted(() => {
  worker.terminate();
});

provide("changeDimensions", changeDimensions);
</script>

<style lang="less" scoped>
.header-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 160px;
  background: url("@/assets/img/dashboard/header.png") no-repeat;
  background-size: 100% 100%;
}

.login-out {
  background: url("@/assets/img/home/bg-5.png") no-repeat center center;
  background-size: 100% 100%;
}

.dimensions {
  background: url("@/assets/img/home/dimensions.png") no-repeat center center;
  background-size: 100% 100%;
}

.dimensions-a {
  background: url("@/assets/img/home/dimensions-active.png") no-repeat center center;
  background-size: 100% 100%;
}

#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.footer {
  background: url("@/assets/img/home/bg-8.png") no-repeat center center;
  background-size: 100% 100%;

  .arc-btn {
    background: url("@/assets/img/home/bg-3.png") no-repeat center center;
    background-size: 100% 100%;

    .tool-btn {
      background: url("@/assets/img/home/bg-4.png") no-repeat center center;
      background-size: 100% 100%;
    }
  }
}
</style>


<style lang="less" scoped>
:deep(.el-input__wrapper) {
  background: rgba(60, 150, 180, 0.5);
  /* 半透明蓝绿色 */
  backdrop-filter: blur(4px);
  /* 磨砂效果 */
  border: 1px solid #6ec6e2;
  box-shadow: none;

  .el-input__inner {
    color: white;
  }
}

:deep(.el-range-input) {
  color: white;
}

:deep(.el-date-editor.el-input,
  .el-date-editor.el-input__wrapper) {
  box-shadow: none;
}

:deep(.el-range__icon),
:deep(.el-range-input),
:deep(.el-range-separator){
  color: #fff !important;
}

:deep(.el-picker__popper.el-popper),
:deep(.el-picker__popper.el-popper .el-popper__arrow:before) {
  background: #429ea5;
  backdrop-filter: blur(10px);
  border: none;
  color: white;
  font-weight: bold;
}

:deep(.el-date-range-picker) {
  background: #429ea5;
  border: none;
  color: white;
}

/* 针对自定义popper-class的样式 */
:global(.popperClass) {
  background: rgba(60, 150, 180, 0.5);
  /* 半透明蓝绿色 */
  backdrop-filter: blur(10px);
  border: none !important;
  color: white !important;
  font-weight: bold !important;
}

:global(.el-picker-panel__shortcut),
:global(.el-date-range-picker__header-label) {
  color: #fff !important;
}

:global(.popperClass .el-popper__arrow:before) {
  background: #429ea5 !important;
  border: none !important;
}

:global(.popperClass .el-date-range-picker) {
  background: #429ea5 !important;
  border: none !important;
  color: white !important;
}

:global(.popperClass .el-date-table th),
:global(.popperClass .el-picker-panel__icon-btn .el-icon),
:global(.popperClass .el-date-table td) {
  color: white !important;
}

:global(.popperClass .el-date-table td.in-range .el-date-table-cell) {
  background: rgba(10, 30, 105, 0.5) !important;
}

:global(.popperClass .el-date-table td.available:hover .el-date-table-cell) {
  background: rgba(255, 255, 255, 0.1) !important;
}

:global(.popperClass .el-date-table td.current:not(.disabled) .el-date-table-cell) {
  background: #6ec6e2 !important;
  color: white !important;
}

.in-range {
  background: rgba(10, 30, 105, 0.5);
}

.el-date-table td.in-range .el-date-table-cell {
  background: none;
}

.el-date-table th,
.el-picker-panel__icon-btn .el-icon {
  color: white;
}
</style>
